package com.code.helper;

import com.code.commons.util.CollectionUtil;
import com.code.commons.util.JsonUtil;
import com.code.commons.util.SignatureUtil;
import com.code.model.vo.az.FastNewsBodyVO;
import com.code.model.vo.az.FastNewsContentVO;
import com.code.model.vo.az.FastNewsDataVO;
import com.code.model.vo.az.FastNewsResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: whitecoin-dapp-parent
 * @description: 快讯信息帮助类
 * @author: hongchun
 * @date: 2020-02-16 10:34
 **/
@Slf4j
public class FastNewsHelper {

    private final static int max_news_limit = 20;

    private static Map<String, FastNewsContentVO> fastNewsMap = new HashMap<>();

    private static List<FastNewsContentVO> fastNewsList;

    public static FastNewsResponseVo getFastNews() {
        List<FastNewsContentVO> contents = fastNewsList == null ? Collections.EMPTY_LIST : fastNewsList;
        FastNewsBodyVO body = FastNewsBodyVO.builder().content(contents).build();
        FastNewsDataVO data = FastNewsDataVO.builder().body(body).build();
        return FastNewsResponseVo.builder().data(data).build();
    }

    /**
     * 聚合快讯信息
     *
     * @param newsKey
     * @param newsChannel
     * @param newsUrl
     */
    public static void generateFastNews(String newsKey, String newsChannel, String newsUrl) {
        try {
            Map data = new LinkedHashMap();
            data.put("businessNo", "B100000");
            data.put("tag", "recommend");
            data.put("requestId", UUID.randomUUID());
            data.put("id", "");
            //获取sign
            String sign = SignatureUtil.signature(newsKey, JsonUtil.object2Json(data), "SHA-512", "UTF8");
            Map remoteData = new HashMap();
            remoteData.put("channel", newsChannel);
            remoteData.put("sign", sign);
            remoteData.put("data", data);
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map> entity = new HttpEntity<>(remoteData, headers);
            HttpEntity<FastNewsResponseVo> response = restTemplate.exchange(newsUrl, HttpMethod.POST, entity, FastNewsResponseVo.class);
            FastNewsResponseVo body = response.getBody();
            if (body != null && CollectionUtil.isNotEmpty(body.getData().getBody().getContent())) {
                List<FastNewsContentVO> contents = body.getData().getBody().getContent();
                Map<String, FastNewsContentVO> newMap = contents.stream().collect(Collectors.toMap(FastNewsContentVO::getId, Function.identity()));
                fastNewsMap.putAll(newMap);
                removeOldestElements();
            }
        } catch (Exception e) {
            log.error("generateFastNews error", e);
        }
    }

    /**
     * 移除旧的element
     *
     */
    private static void removeOldestElements() {
        List<FastNewsContentVO> sortFastNews = fastNewsMap.values().stream().sorted(Comparator.comparing(FastNewsContentVO::getPublishDate).reversed()).collect(Collectors.toList());
        int overLimits = fastNewsMap.size() - max_news_limit;
        if (overLimits > 0) {
            List<FastNewsContentVO> toDelElements = new ArrayList<>(overLimits);
            for (int i = 1; i <= overLimits; i++) {
                int index = sortFastNews.size() - i;
                FastNewsContentVO contentVO = sortFastNews.get(index);
                fastNewsMap.remove(contentVO.getId());
                toDelElements.add(contentVO);
            }
            //移除元素
            sortFastNews.removeAll(toDelElements);
        }
        fastNewsList = sortFastNews;
    }

}
